import configparser
from configparser import Interpolation
from functools import wraps
from lly.logconfig import logger

'''合成nvim配置并执行'''


class VimMappingManger():
    '''nvim配置操作
    '''

    def __init__(self, nvim, result_path=None, replace_str="{abs_op}"):
        self.nvim = nvim
        self.config = self._getConfigParser()
        self.result_path = result_path
        if self.result_path is None:
            self.result_path = '.mapping.vim'
        self.replace_str = replace_str

    def _getConfigParser(self):
        return configparser.ConfigParser(interpolation=Interpolation())

    def import_mapping_file(self, filepath):
        if len(self.config.sections()) == 0:
            self.config.read(filepath, encoding='utf-8')
        else:
            change_config = self._getConfigParser()
            change_config.read(filepath, encoding='utf-8')
            for section in change_config.sections():
                if self.config[section] is None:
                    self.config[section] = {}
                for key in change_config[section]:
                    self.config[section][key] = change_config[section][key]

    def import_function(self, filepath):
        logger.exception(self)
        logger.exception(filepath)
        function = self._getConfigParser()
        function.read(filepath, encoding='utf-8')
        with open(self.result_path, 'w', encoding='utf-8') as f:
            f.writelines(['"function ---'+filepath+'\n'])
            for section in function.sections():
                lose_section = False
                temp_list = []
                temp_list.append(f'"section:{section}:------\n')
                if not self.config.has_section(section) or self.config[section] is None:
                    lose_section = True
                elif self.config.has_option(section, 'mapleader'):
                    mapleader = self.config[section]['mapleader']
                    temp_list.append(f'let mapleader_temp=mapleader\n')
                    if mapleader is not None:
                        temp_list.append(
                            f'let mapleader={ repr(mapleader) }\n')

                for key in function[section]:
                    cmd_sample = function[section][key]
                    #  print(f'section \n {key}:{cmd_sample}')
                    if lose_section or self.config[section][key] is None:
                        temp_list.append('"lose :'+cmd_sample+'\n')
                    else:
                        cmd = cmd_sample.replace(
                            self.replace_str, self.config[section][key], 1)
                        temp_list.append(cmd+'\n')
                temp_list.append(f'let mapleader=mapleader_temp\n')

                #  logger.info(f'{section} :{"|".join(temp_list)}')
                f.writelines(temp_list)
        self.nvim.command(
            f'let g:python_mapping_result_file={repr(self.result_path)}')
        self.nvim.command(f'source {self.result_path}')

    def clear_mapping(self):
        self.config.clear()
